package middleware

import (
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//token := c.GetHeader(config.HeaderLoginToken)
		signToken := c.GetHeader(config.HeaderLoginToken)
		//fmt.Println("auth middleware", signToken)
		// 验证 token 格式
		if signToken == "" || !strings.HasPrefix(signToken, "Bearer") {
			response.Response(c, http.StatusUnauthorized, code.AuthorizationError, code.Text(code.AuthorizationError), gin.H{})
			c.Abort()
			return
		}
		tokenStr := signToken[7:]
		_, _, err := util.ParseToken(tokenStr)
		if err != nil {
			// token 验证失败
			response.Response(c, http.StatusUnauthorized, code.AuthorizationError, err.Error(), gin.H{})
			c.Abort()
			return
		}
		//fmt.Println("claims", claims) //claims &{1 { 1681046224  1680441424 ygl 0 user token}}

		c.Set("token", tokenStr)
		// 验证通过
		c.Next()
	}
}
